package purchase

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

func taxFee(r *gin.RouterGroup) {
	product := r.Group("/tax")
	{
		product.POST(sql.RequestAdd, taxFeeAdd)
		product.POST(sql.RequestUpdate, taxFeeUpdate)
		product.GET(sql.RequestData, taxFeeData)
		product.GET(sql.RequestDelete, taxFeeDelete)
	}
}

func taxFeeData(c *gin.Context) {
	sql.HttpData(c, &model.TaxFee{}, func(db *gorm.DB) *gorm.DB {
		if containerNO := c.Query("containerNo"); containerNO != "" {
			db = db.Where("container_no = ?", containerNO)
		} else {
			db.Error = errors.New(sql.ErrorParams)
		}
		return db
	})
}

func taxFeeAdd(c *gin.Context) {
	taxFeeEdit(sql.ADD, c)
}

func taxFeeUpdate(c *gin.Context) {
	taxFeeEdit(sql.UPDATE, c)
}

func taxFeeDelete(c *gin.Context) {
	sql.HttpDelete(c, &model.TaxFee{}, nil)
}

func taxFeeEdit(action string, c *gin.Context) {
	sql.HttpHandle(action, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var bean model.TaxFee
		if err := sql.PostParamsBind(c, db, &bean).Error; err != nil {
			return db, nil
		}
		decimal.NewFromFloat(bean.Tariff)
		total := decimal.NewFromFloat(bean.Tariff).
			Add(decimal.NewFromFloat(bean.ValueAddedTax)).
			Add(decimal.NewFromFloat(bean.TaxDifference))
		if total.InexactFloat64() != bean.TotalFee || bean.TotalFee == 0 {
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}

		if action == sql.ADD {
			db = db.Create(&bean)
		} else if action == sql.UPDATE {
			db = db.Updates(&bean)
		}
		return db, bean
	})
}
